package com.example.ocridentification.study;

import com.example.ocridentification.config.ImageToBase64;
import com.example.ocridentification.model.ImageBody;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.*;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.io.IOException;

@SpringBootTest
public class Demo {
    @Autowired
    private OkHttpClient okHttpClient;
    @Autowired
    private ObjectMapper objectMapper;

    private String appcode = "c8518f45d5334300b73c638e299820ab";
    private String imagePath = "D:\\image\\r2.jpg";

    @Test
    public void base64(){
        try {
            String s = ImageToBase64.imageToBase64(imagePath);
            System.out.println(s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void test() {
        try {
            // 1. 准备请求体
            ImageBody body = new ImageBody();
            body.setImg(ImageToBase64.imageToBase64(imagePath));

            // 2. 确保APPCODE正确

            // 3. 创建请求
            MediaType JSON = MediaType.get("application/json; charset=utf-8");
            String jsonBody = objectMapper.writeValueAsString(body);

            Request request = new Request.Builder()
                    .url("https://bdcqz.market.alicloudapi.com/ocrservice/estateCert")
                    .post(RequestBody.create(jsonBody, JSON))
                    .addHeader("Authorization", "APPCODE " + appcode)
                    .addHeader("Content-Type", "application/json; charset=UTF-8")
                    .build();

            // 4. 执行请求并处理响应
            try (Response response = okHttpClient.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    String errorBody = response.body().string();
                    throw new IOException(
                            "API请求失败:\n" +
                                    "状态码: " + response.code() + "\n" +
                                    "错误信息: " + response.message() + "\n" +
                                    "响应体: " + errorBody
                    );
                }

                String responseData = response.body().string();
                System.out.println("识别结果: " + responseData);
            }
        } catch (Exception e) {
            System.err.println("发生错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
